package com.itheima.service.impl;

import com.itheima.dto.UserLoginDTO;
import com.itheima.entity.SysUser;
import com.itheima.mapper.LoginMapper;
import com.itheima.service.LoginService;
import com.itheima.vo.UserLoginVO;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
       SysUser sysUser= loginMapper.selectByName(userLoginDTO.getLogin_name());
        if (!sysUser.getLoginName().equals(userLoginDTO.getLogin_name())) {
            throw new RuntimeException("用户名错误");
        }
        String password = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        if (!password.equals(sysUser.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", sysUser.getId());
        String itheima = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, "itheima")
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 3600))
                .compact();
        UserLoginVO userLoginVO = new UserLoginVO(itheima);
        return userLoginVO;
    }
}
